import React, {PureComponent} from 'react';
import {
    View, Text, ActivityIndicator,
    Image,
    StyleSheet
} from 'react-native';

import Swiper from 'react-native-swiper'

export default class Carousel extends PureComponent {
    url = 'http://111.230.254.117:8000/gang_rape';

    state = {
        carouselItems: [],
    }

    componentWillMount() {
        this._fetchCarouselItems();
    }

    async _fetchCarouselItems() {
        console.log('Begin fetching carousel items')
        data = await this._doFetch();
        if (data === null) {
            console.log('No carousel items');
            return;
        }
        console.log(`Fetched ${this.state.carouselItems.length} carousels`);
        this.setState({carouselItems: data});
    }

    _doFetch() {
        return fetch(this.url).then(
            resp => resp.text()
        ).then(
            respText => JSON.parse(respText)
        ).catch(err => {
            console.log('Fetching data failed', err);
            return null
        })
    }

    render() {
        const {carouselItems} = this.state;
        return (
            <View style={styles.carousel}>
                {carouselItems.length === 0 && <ActivityIndicator />}
                <Swiper autopaly={true}>
                    {carouselItems.filter(item => item.url_goods_img).map(
                        item => <CarouselItem 
                                    imgUrl={item.url_goods_img}
                                    key={item.id}
                                />
                    )}
                </Swiper>
            </View>
        );
    }
}

class CarouselItem extends PureComponent {
    render() {
        const {imgUrl} = this.props;
        console.log('Carousel item url:', imgUrl);
        // return (
        //     <Image
        //         source={{uri: imgUrl}}
        //         style={styles.carouselItem}
        //     />
        // );
        if (imgUrl) {
            return (
                <Image
                    source={{uri: imgUrl}}
                    style={styles.carouselItem}
                />
            );
        }
        return null;
    }
}

const styles = StyleSheet.create({
    carousel: {
        height: 160,
        justifyContent: 'center',
    },
    carouselItem: {
        width: '100%',
        height: 210,
    },
});